﻿using System;
using MediaBrowserWS.Code;
using System.IO;
using System.Threading;
using MediaBrowserWS.Service;

namespace MediaBrowserWS.Logging
{
    public class Logger
    {
        private static Logger _instance;
        public static Logger Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new Logger();
                }

                return _instance;
            }
        }
        private static readonly object LockObject = new object();
        private static string LogDir = Path.Combine(AppSettings.MediaBrowserWsDirectory.FullName, "Log");

        public void LogMessage(string message, params object[] stringFormatArgs)
        {
            if (AppSettings.Log)
            {
                // Perform logging in a separate thread so as not to impact service call duration
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    lock (LockObject)
                    {
                        FileInfo logFile = new FileInfo(Path.Combine(LogDir, AppSettings.ApplicationStartTime.ToString("yyyyMMddHHmm") + ".txt"));
                        logFile.Directory.EnsureDirectoryExistance();

                        StreamWriter logWriter;

                        try
                        {
                            if (File.Exists(logFile.FullName))
                            {
                                logWriter = new StreamWriter(new FileStream(logFile.FullName, FileMode.Append, FileAccess.Write, FileShare.None));
                            }
                            else
                            {
                                logWriter = new StreamWriter(new FileStream(logFile.FullName, FileMode.CreateNew, FileAccess.Write, FileShare.None));
                            }
                        }
                        catch
                        {
                            throw new ApplicationException("Log file locked");
                        }

                        logWriter.WriteLine(DateTime.Now.ToString() + ": " + string.Format(message, stringFormatArgs));
                        logWriter.Flush();
                        logWriter.Close();
                    }
                });
            }
        }
    }
}
